package com.t174.car.controller;

import com.t174.car.dao.*;
import com.t174.car.entity.Permission;
import com.t174.car.entity.Role;
import com.t174.car.entity.State;
import com.t174.car.entity.UserInfo;
import com.t174.car.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Scope("prototype")//默认到单例模式
public class UserController {
    @Autowired
    private UserInfoDao userInfoDao ;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private UserService userService;
    @Autowired
    private StateDao stateDao;
    @RequestMapping("/index")
    public String login(String userName, String pwd, Model model,HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(userName,pwd) ;
        try {
            subject.login(token);
            UserInfo userInfo = new UserInfo();
            userInfo.setUsername(userName);
            userInfo.setPwd(pwd);
            UserInfo userInfo1 = userInfoDao.login(userInfo);
            System.out.println(userInfo1);
            if(userInfo1!=null){
                if(userInfo1.getState() == 0){
                    State state = stateDao.getStateByUid(userInfo1.getId());
                    request.getSession().setAttribute("msg","禁用:"+state.getState());
                    return "redirect:/login.jsp";
                }
                Role role = roleDao.getRoleByUid(userInfo1.getId());
                if(role == null){
                    request.getSession().setAttribute("msg","用户无角色");
                    return "redirect:/login.jsp";
                }
                List<Permission> list = permissionDao.query(0,userInfo1.getId());
                List<Integer> pids = new ArrayList<>();
                for (Permission p: list) {
                    pids.add(p.getId());
                }
                List<Permission> list2 = null;
                if(pids!=null&&pids.size()>0){
                    list2 = permissionDao.queryByPermissionIds(pids,userInfo1.getId());
                }
                model.addAttribute("menu1", list);
                model.addAttribute("menu2", list2);
                request.getSession().getServletContext().setAttribute("menu1", list);
                request.getSession().getServletContext().setAttribute("menu2", list2);
                request.getSession().getServletContext().setAttribute("role", role);
                request.getSession().getServletContext().setAttribute("user", userInfo1);
                request.getSession().setAttribute("role", role);
                return "redirect:/index.jsp";
            }else{
                request.getSession().setAttribute("msg","用户名或密码错误");
                return "redirect:/login.jsp";
            }

        }  catch (UnknownAccountException e){
            e.printStackTrace();
            request.getSession().setAttribute("msg","用户名不正确!");
            return "redirect:/login.jsp" ;
        }
        catch(AuthenticationException e){
            e.printStackTrace();
            request.getSession().setAttribute("msg","密码不正确!");
            return "redirect:/login.jsp" ;
        }

    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        //
        request.getSession().removeAttribute("role");
        request.getSession().removeAttribute("msg");
        Subject subject = SecurityUtils.getSubject() ;
        //取消认证
        subject.logout();
        return "redirect:/login.jsp" ;
    }
    @RequestMapping("/queryuser")
    @ResponseBody
    public List<UserInfo> queryuser(){
        return userInfoDao.query();
    }
    @RequestMapping("/queryrole")
    @ResponseBody
    public Map<String,Object> queryRole(Integer uid){
        Map<String,Object> map = new HashMap<>();
        map.put("list",roleDao.query());
        map.put("role",roleDao.getRoleByUid(uid));
        return map;
    }
    @RequestMapping("/updateRole")
    @ResponseBody
    public Integer updateRole(Integer uid,Integer rid){
        Role role = roleDao.getRoleByUid(uid);//查询用户权限
        int count = 0;
        if(role!=null){
            count = userRoleDao.updateRoleByUid(uid,rid);
        }else{
            count = userRoleDao.addRole(uid,rid);
        }

        return count;
    }
    @RequestMapping("/updateState")
    @ResponseBody
    public Integer updateState(Integer uid, Integer state){
        int count = userInfoDao.updateState(uid,state);
        return count;
    }
    @RequestMapping("/userAdd")
    @ResponseBody
    public Integer addUser(UserInfo userinfo){
        int count = userInfoDao.addUserinfo(userinfo);
        return count;
    }
    @RequestMapping("/upUser")
    @ResponseBody
    public Integer upUser(UserInfo userInfo){
        return userInfoDao.upUserinfo(userInfo);
    }
    @RequestMapping("/delUser")
    @ResponseBody
    public Integer delUser(String ids){
        String[] ss = ids.split("-");
        Integer[] myids = new Integer[ss.length] ;
        for(int i=0;i<ss.length;i++){
            myids[i] = Integer.parseInt(ss[i]) ;
        }
        return userService.delUser(myids);
    }
    @RequestMapping("/getUserByRole")
    @ResponseBody
    public List<UserInfo> getUserByRole(int oid){
       return userInfoDao.getUserByRole(oid);
    }
}
